#!/bin/bash

# Constants
NAME="check_logwarn"
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3

# We want to get the error result of logwarn(1), not sed(1), so set "pipefail" bash option
set -o pipefail

# Create temporary file for stderr output
ERROUT_FILE=`mktemp -q /tmp/check_logwarn.XXXXXX`
if [ $? -ne 0 ]; then
    echo "CRITICAL - Can't create temporary file"
    exit ${STATE_CRITICAL}
fi
trap "rm -f ${ERROUT_FILE}" 0 2 3 5 10 13 15

# Run logwarn and grab a sample of the log messages matched (up to 80 chars)
LOG_MESSAGE=`logwarn ${1+"$@"} 2>"${ERROUT_FILE}" | tr '\n' ' ' | sed -r 's/^(.{77}).+$/\1.../g'`
LOGWARN_EXIT="$?"

# If there was an error, output put the stderr message instead
if [ ${LOGWARN_EXIT} -gt 1 ]; then
    LOG_MESSAGE=`cat "${ERROUT_FILE}" | tr '\n' ' ' | sed -r 's/^(.{77}).+$/\1.../g'`
fi

# Remove temporary file
rm -f "${ERROUT_FILE}"
trap - 0 2 3 5 10 13 15

# Output result based on exit value from logwarn(1)
case $LOGWARN_EXIT in
    0)
        echo "OK: No log errors found"
        exit ${STATE_OK}
        ;;
    1)
        echo "WARNING: Log errors found: ${LOG_MESSAGE}"
        exit ${STATE_WARNING}
        ;;
    *)
        echo "UNKNOWN: logwarn(1) error: ${LOG_MESSAGE}"
        exit ${STATE_UNKNOWN}
        ;;
esac

